package com.ln.point.service;

import com.ln.adoms.dao.GoodsDao;
import com.ln.adoms.dao.QrGoodsCodeDao;
import com.ln.adoms.entity.Goods;
import com.ln.adoms.entity.Marchandise;
import com.ln.adoms.entity.QrGoodsCode;
import com.ln.adoms.entity.neum.DepartType;
import com.ln.adoms.entity.neum.Status;
import com.ln.core.utils.EncryptUtils;
import com.ln.point.dao.PointMemberDao;
import com.ln.point.dao.PointRecordDao;
import com.ln.point.entity.PointMember;
import com.ln.point.entity.PointRecord;
import com.ln.point.entity.PointType;
import com.ln.sms.entity.Sms;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
@Transactional
public class SmsPointServer {

    @Resource
    private PointMemberDao pointMemberDao;

    @Resource
    private QrGoodsCodeDao qrGoodsCodeDao;

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private PointRecordDao pointRecordDao;


    public HashMap<String, String> doPoints(Sms sms) {


        HashMap<String, String> msgMap = null;

        // 1.门店销售后才可以积分
        // String hql = "from QrGoodsCode where iCode = ? and state = ?";
        // QrGoodsCode qr = (QrGoodsCode) HibernateUtils.createQuery(session, hql, sms.getContent().trim(), Status.QR_ABLE_INTEGRAL.getValue()).uniqueResult();
        //
        String iCode = sms.getContent().trim().replaceAll(" ", "");

        // 2.省代出库后就可以积分（2013.04.21）
        //String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
        //		+ "(select dt.id from DepartmentType dt where dt.name=?)) and g.state = ? and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";
//        List<QrGoodsCode> qrList = HibernateUtils.createQuery(session, hql, DepartType.SD.v(), Status.HAS_OUT.getValue(), iCode, Status.QR_HAD_INTEGRAL.getValue()).list();

        //2.到省代了就可以积分（2013.08.06 - 2013-10-10）
        String hql = "from QrGoodsCode where id in (select g.qrCode.id from Goods g where g.department.id in (select dd.id from Department dd where dd.type.id in "
                + "(select dt.id from DepartmentType dt where dt.name != ?))  and g.qrCode.id = " + "(select qq.id from QrGoodsCode qq where qq.iCode = ? and qq.state != ?))";

        @SuppressWarnings("unchecked")
        List<QrGoodsCode> qrList = qrGoodsCodeDao.findList(hql, DepartType.ZD.v(), iCode, Status.QR_HAD_INTEGRAL.getValue());

        if (qrList != null && !qrList.isEmpty()) {
            QrGoodsCode qr = qrList.get(0);
            hql = "from Goods where qrCode.id = ?";
            @SuppressWarnings("unchecked")
            List<Goods> goodsList = goodsDao.findList(hql, qr.getId());
            if (goodsList != null && goodsList.size() > 0) {
                msgMap = new HashMap<String, String>();

                Marchandise m = goodsList.get(0).getMarchandise();
                Double point = m.getPoint();
                String mobile = sms.getMobile().trim();

                hql = "from PointMember where mobile = ?";
                boolean isNewMember = false;
                //2014.02.10
//                PointMember member = (PointMember) HibernateUtils.createQuery(session, hql, mobile).uniqueResult();
//                if (member == null) {
//                    member = new PointMember();
//                    member.setUserName(mobile);
//                    member.setMobile(mobile);
//                    member.setPassword(EncryptUtils.md5(mobile));
//                    member.setInsertTime(new Date());
//                    session.save(member);
//                    isNewMember = true;
//                }

                //2014.02.10
                PointMember member = null;
                List<PointMember> members = pointMemberDao.findList(hql, mobile);

                if (members == null || members.size() == 0) {
                    member = new PointMember();
                    member.setUserName(mobile);
                    member.setMobile(mobile);
                    member.setPassword(EncryptUtils.md5(mobile));
                    member.setInsertTime(new Date());
                    pointMemberDao.save(member);
                    isNewMember = true;
                } else {
                    member = members.get(0);
                    if (members.size() > 1) {
                        System.err.println("--------- Please check duplicate member's mobile number：" + mobile + " ---------");
                    }
                }

                Double balance = point + member.getBalance();
                member.setBalance(balance); // 给会员加积分
                pointMemberDao.update(member);
                // 记录积分记录
                PointRecord record = new PointRecord();
                record.setBalance(balance);
                record.setPoint(point);
                record.setMember(member);
                record.setType(PointType.POINT);
                record.setInsertTime(new Date());
                record.setiCode(iCode);
                record.setOper("SYMTEM");
                pointRecordDao.save(record);
                qr.setState(Status.QR_HAD_INTEGRAL.getValue());
                qrGoodsCodeDao.update(qr);
                if (isNewMember) {
                    // 新顾客：尊敬的客户，您已成功积分100（50）分，兑换规则可登录www.qingyunit.com查询。客服热线4000-800-866【轻云服务】。（68字）
                    msgMap.put("尊敬的客户，", "您已成功积分" + point + "分，兑换规则可登录www.qingyunit.com查询。客服热线4000-800-866【轻云信息】");
                } else {
                    // 老顾客：尊敬的顾客XXX（系统调出名字），您已成功积分100（50）分，目前积分余额为XXXX分。客服热线4000-800-866【轻云服务】（65字）。
                    msgMap.put("尊敬的顾客，" + member.getUserName(), "您已成功积分" + point + "分，目前积分余额为" + balance + "分。客服热线4000-800-866【轻云信息】");
                }
            }

        }
        if (msgMap == null) {
            msgMap = new HashMap<String, String>();
            // 尊敬的客户，您的输入有误，请核实后重新发送。如有疑问可拨打轻云服务咨询热线4000-800-866
            msgMap.put("尊敬的客户，", "您的输入有误，请核实后重新发送。如有疑问可拨打轻云信息咨询热线4000-800-866【轻云信息】");
        }
        return msgMap;
    }
}
